/*
 * =====================================================================================
 *
 *       Filename:  process_server.cpp
 *
 *    Description:  每个客户端一个子进程的通信模型
 *
 *        Version:  1.0
 *        Created:  2008年09月17日 16时37分35秒
 *       Revision:  none
 *       Compiler:  g++
 *
 *         Author:  ZhixiongHong (hzx), fishwarter@gmail.com
 *        Company:  Unioncast
 *
 * =====================================================================================
 */

#include "cs_common.h"

int main(int argc, char** argv)
{
	if( argc !=2 )	
	{
		cout << "usage: " << argv[0] << " <#port>" << endl;
		return -1;
	}
	unsigned short port = (unsigned short )atoi(argv[1]);
	
	void sig_chld(int);
	void sig_int(int);
	void web_child(int);

    pid_t       childpid;
    int         listenfd, connfd;
    socklen_t   clilen;
    struct      sockaddr_in cliaddr, servaddr;

	signal(SIGCHLD, sig_chld);
	signal(SIGINT, sig_int);
    signal(SIGPIPE, SIG_IGN);

    listenfd = socket(AF_INET, SOCK_STREAM,0);
    if(listenfd < 0)
    {
        cout << "create listenfd error " << strerror(errno) << endl;
        return -1;
    }

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(port);
    
    const int on = 1;
    setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
    int retint = bind(listenfd, (sockaddr *)&servaddr, sizeof(servaddr));
    if( retint)
    {
        cout << "bind listenfd error: "  << strerror(errno) << endl;
        return -1;
    }
    
    retint = listen(listenfd, LISTENQ);
    if( retint)
    {
        cout << "listen error " << strerror(errno) << endl;
        return -1;
    }
	
    cout << "in " << argv[0] << "start svr at " << port << endl;
    for(; ;)
    {
        clilen = sizeof(cliaddr);
        connfd = accept(listenfd, (sockaddr *)&cliaddr, &clilen);
        cout << "accept new connection......." << endl;
        if( connfd > 0 )
        {
            if( (childpid = fork()) == 0)
            {
                close(listenfd);
                web_child(connfd);
                exit(0);
            }
            cout << "close conn socket " << endl;
            close(connfd);
        }
    }
    return 0;
}





void sig_int(int signo)
{
	pr_cpu_time();
	exit(0);
}

void sig_chld(int signo)
{

}
